<?php
/**
 * Created by b17
 * 3/23/12 6:26 PM
 */

namespace Managers\Text\Filter;

use Managers\Builder\GenericBuilder,
    G4T\Util\Words,
    Managers\Builder\BadWordsBuilder;

class StopWordFilter extends GenericFilter
{
    /**
     * QueryBuilder для стоп-слов.
     *
     * @var \Managers\Builder\GenericBuilder
     */
    private $_builder;

    private $_badWords;

    private $_foundWords = array();

    public function __construct()
    {
        parent::__construct();
        $this->_builder = new BadWordsBuilder();
        $this->_load();
    }

    private function _load()
    {
        if (is_null($this->_badWords)) {
            $words = $this->_builder->getArrayResult();
            $badWords = array();
            foreach ($words as $word) {
                $badWords = array_merge($badWords, Words::getWords($word['word']));
            }
            $this->_badWords = $badWords;
        }
    }

    public function sanitize($content)
    {
        setlocale(LC_ALL, "ru_RU.UTF-8");
        $badWordsPattern = join('|', $this->_badWords);
        $pattern = sprintf('/(^|\s|\W)(%s)(\s|$|\W)/iu', $badWordsPattern);
        return  preg_replace_callback($pattern, array($this, '_highlight'), $content);
    }

    private function _highlight(array $matches)
    {
        $this->_foundWords[] = $matches[0];
        return mb_strtoupper($matches[0]);
    }

    public function hasErrors()
    {
        return count($this->_foundWords) > 0;
    }

    public function getFoundWords()
    {
        return array_unique($this->_foundWords);
    }
}
